import eventbus from '@/eventBus';
import {
    debounce
} from '@/util/index';
import defaultGif from '@/assets/default.gif';
//图片信息数组
let imgs = [];
//该函数实现处理单张图片,传入要处理的图片
function setImage(img){
    img.dom.src = defaultGif;
    const clientHeight = document.documentElement.clientHeight;
    const rect = img.dom.getBoundingClientRect();
    const height = rect.height || 150;
    if(rect.top>=-height&&rect.top<=clientHeight){
        //在视口范围内
        const tempImg = new Image();
        tempImg.onload=function(){
            img.dom.src =img.src
        }
        tempImg.src = img.src;
        imgs = imgs.filter(i=>{
            i!==img;
        })
    }
   


}
//调用该函数可以找到对应该加载的图片
function setImages() {
    for (const img of imgs) {
        //遍历循环所有要处理的图片
        setImage(img);
    }
}

function handleScroll() {
    setImages();
}

// setInterval(() => {
//     console.log(imgs);
// }, 2000);
eventbus.$on('mainScroll', debounce(handleScroll, 50))
export default {
    inserted(el, bindings) {
        const img = {
            dom: el,
            src: bindings.value,
        };
        imgs.push(img);
        setImage(img);
    },
    unbind(el) {
        imgs = imgs.filter(img => {
            img.dom !== el
        })
    }
}